package eu.ict_omelette.mashup.compositionminer;

import eu.ict_omelette.mashup.adapters.pipes.PipesAdapter;
import eu.ict_omelette.mashup.canonicalmodel.CanonicalMashup;
import eu.ict_omelette.mashup.canonicalmodel.Component;
import eu.ict_omelette.mashup.canonicalmodel.Dataflow;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.net.URI;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Vector;

public class MainCrowd {

    private static CompositionMiner cm = new CompositionMiner();
    public static List <CanonicalMashup> listPatterns = null;

    public static void main(String args[]){

        loadPipes("/tmp/pipes_998");
        listPatterns = cm.mineMultiCompPattern(0.0021, 0.00, 0.00);
        //printPatterns();
        printSelectedComps();

        //randomPickPatterns();
    }

    private static void randomPickPatterns(){
        BufferedReader br = null;

        try {

                String sCurrentLine;
                int lineCount = 0;

                Vector<String> v = new Vector<String>();

                br = new BufferedReader(new FileReader("/Users/carlos/Dropbox/CrowdPipe/Patterns/Pattern-A40-Automated-Algorithm.txt"));

                while ((sCurrentLine = br.readLine()) != null) {
                        v.add(sCurrentLine);
                }

                br.close();

                Random randomGenerator = new Random();

                for(int i = 1; i <= 42; i++){
                    int randomInt = randomGenerator.nextInt(v.size()) + 1;

                    String pat = v.get(randomInt);
                    System.out.println(pat);

                    v.remove(randomInt);
                }

                

                

        } catch (Exception e) {
                e.printStackTrace();
        } finally {
                try {
                        if (br != null)br.close();
                } catch (Exception ex) {
                        ex.printStackTrace();
                }
        }
    }

    private static void printPatterns(){
        Iterator<CanonicalMashup> it = listPatterns.iterator();
        //Iterator<CanonicalMashup> it = cm.getRepo();
        while(it.hasNext()){
            CanonicalMashup m = it.next();

            Iterator<Component> cmpIt = m.getComponents();
            System.out.println("=======================================");
            System.out.println("[MODULES]");
            while(cmpIt.hasNext()){
                Component comp = cmpIt.next();
                System.out.println("\t" + comp.getType() + "("+ comp.getId() +")");
            }

            System.out.println("[DATAFLOWS]");
            Iterator<Dataflow> dfIt = m.getDataFlows();
            while(dfIt.hasNext()){
                Dataflow df = dfIt.next();

                System.out.println("\t" + df.getFromComponent().getType() + "[" +
                        df.getFromPort().getName() + "]" + " => " + df.getToComponent().getType() + "[" +
                        df.getToPort().getName() + "]" );
            }
        }


    }

    private static void printSelectedComps(){

        Iterator<CanonicalMashup> patIt = listPatterns.iterator();

        int patCount = 0;

        while(patIt.hasNext()){
            CanonicalMashup pat = patIt.next();            

            Iterator<CanonicalMashup> cmIt = cm.getRepo();
            while(cmIt.hasNext()){
                CanonicalMashup cMash = cmIt.next();


                /*
                Component c1 = pat.getComponent("sw-101");
                Component c2 = cMash.getComponent("sw-73");

                if((c1 != null) && (c2 != null)){
                    if(c1.getType().equals("loop") && c2.getType().equals("textinput"))
                        System.out.println("\n\n\nTHIS IS WHAT I AM LOOKING FOR: " + cMash.getId() + "\n\n\n");
                }
                 */

                Iterator<Dataflow> dfPatIt = pat.getDataFlows();
                Iterator<Dataflow> dfCmIt = cMash.getDataFlows();

                Vector<String> v = new Vector<String>();
                Hashtable<String, String> selComps = new Hashtable<String, String>();

                int countDfPat = 0;
                int countMatch = 0;
                while(dfPatIt.hasNext()){
                    Dataflow patDf = dfPatIt.next();
                    countDfPat++;

                    while(dfCmIt.hasNext()){
                        Dataflow cmDf = dfCmIt.next();

                        if( patDf.getFromComponent().getType().equals(cmDf.getFromComponent().getType()) &&
                            patDf.getToComponent().getType().equals(cmDf.getToComponent().getType()) &&
                            patDf.getFromPort().getName().equals(cmDf.getFromPort().getName()) &&
                            patDf.getToPort().getName().equals(cmDf.getToPort().getName())
                           ){

                                countMatch++;
                                selComps.put(cmDf.getFromComponent().getId(), cmDf.getFromComponent().getId());
                                selComps.put(cmDf.getToComponent().getId(), cmDf.getToComponent().getId());

                                break;

                        }
                                
                            
                    }


                }

          
                if(countDfPat == countMatch){
                    patCount++;
                    String pipeId = cMash.getId();

                    //We get only the Pipe ID:
                    pipeId = pipeId.substring(22, pipeId.length());

                    Enumeration<String> en = selComps.keys();
                    String lstComps = "";
                    while(en.hasMoreElements()){
                        String c = en.nextElement();

                        lstComps = lstComps + c + "#";
                    }

                    lstComps = lstComps.substring(0, lstComps.length() - 1);

                    System.out.println(patCount + "," + pipeId + "," + lstComps);

                }                
                
                
            }

        }


    }


    private static void loadPipes(String din){
                
        try{

            String dirPath = din;
            File dir = new File(dirPath);

            if(!dir.exists()){
                System.out.println("Directory does not exists: " + din);
                System.exit(1);
            }

            String[] children = dir.list();


            if(children == null){
                System.out.println("No files to mine in: " + din);
                System.exit(1);
            }

            for(int i = 0; i < children.length; i++){
                
                String filename = children[i];
                String filepath = "";
                //if(i >= 70) break;
                if(filename.contains("pipe")){
                    filepath = dirPath + "/" + filename;
                }else{
                    continue;
                }
                
                File jsonFile = new File(filepath);
                URI uri = jsonFile.toURI();
                
                PipesAdapter adapter = new PipesAdapter();
                adapter.loadSourceMashupModel(uri);                
                cm.addCompositionToRepo(adapter.getCanonicalMashup());
            }

            System.out.println("REPOSITORY SIZE: " + cm.getRepoSize());

        }catch(Exception e){
            e.printStackTrace();
        }
    }

    

}